package com.zerdoor.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zerdoor.model.ChatingRecord;
import com.zerdoor.model.UserInfo;
import com.zerdoor.util.chatRecord.ChatingRecordOperation;

import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.servlet.Pushlet;
import nl.justobjects.pushlet.util.Log;
import nl.justobjects.pushlet.util.Servlets;

public class ChatServlet extends Pushlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Event event = null;
		try {
			// Event parm identifies event type from the client
			String eventType = Servlets.getParameter(request, P_EVENT);

			// Always must have an event type
			if (eventType == null) {
				Log.warn("Pushlet.doGet(): bad request, no event specified");
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No eventType specified");
				return;
			}

			// Create Event and set attributes from parameters
			event = new Event(eventType);
			for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
				String nextAttribute = (String) e.nextElement();
				event.setField(nextAttribute, request.getParameter(nextAttribute));
			}
			
			if(event.getField("userID") != null && event.getField("msg") != null){
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dataTime = sdf.format(new Date());
				//加入服务端时间
				event.setField("sendTime", dataTime);
				//解编码
				String msg = java.net.URLDecoder.decode(event.getField("msg"),"UTF-8");
				String nick = java.net.URLDecoder.decode(event.getField("nick"),"UTF-8");
				
				String path = request.getSession().getServletContext().getRealPath("") ;
				
				String channel = event.getField("p_subject");

                //获取session中的当前对象
                UserInfo userInfo = (UserInfo) request.getSession().getAttribute("curUser");


                //聊天记录实体对象
				ChatingRecord cr = new ChatingRecord();

                cr.setUserId(userInfo.getUserId().toString());
				cr.setSendUserName(userInfo.getNickname());
				cr.setDataTime(dataTime);
				cr.setMassage(msg);
                cr.setHeadPortrait(userInfo.getHeadPortrait());

                //持久化
				ChatingRecordOperation.saveChatingRecords(path,channel,cr);
				
			}
			

		} catch (Throwable t) {
			// Error creating event
			Log.warn("Pushlet: Error creating event in doGet(): ", t);
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}

		// Handle parsed request
		doRequest(event, request, response);
	}

	
	
	

}
